/**
 * JMS规范中的消息类型：TextMessage、MapMessage、ObjectMessage、BytesMessage和StreamMessage等五种
* 1.建立ConnectionFactory工厂对象，需要填入用户名、密码、连接地址（一般使用默认，如果没有修改的话）
* 2.创建一个Connection连接，并且调用Connection的start方法开启连接，Connection方法默认是关闭的
* 3.创建Session会话(connection.createSession)，用于接收消息，参数1是是否启用事务，参数2是签收模式，一般设置为自动签收
* 4.创建Destination队列(session.createQueue)，指的是一个客户端用来制定生产消息目标和消费消息来源的对象。在PTP的模式中，Destination被称作队列，在Pub/Sub模式中，Destination被称作主题（Topic）
* 5.创建消息生产者MessageProducer(session.createProducer)
* 6.设置MessageProducer的相关属性(producer.setDeliveryMode)
* 7.创建消息内容TextMessage（session.createTextMessage），
 *8.发送消息(producer.send)
 *9.释放资源,session.close、connection.close
*/
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

public class QueueProducer {

    public static void main(String[] args) throws JMSException {

        Connection connection = null;
        Session session = null;
        /*等效替换
        QueueConnection connection = null;
        QueueSession session = null;*/

        try {
            ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnectionFactory.DEFAULT_USER,
                    ActiveMQConnectionFactory.DEFAULT_PASSWORD, "tcp://localhost:61616");
            connection = connectionFactory.createConnection();
            connection.start();
            session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
            Destination destination = session.createQueue("myqueue");
            MessageProducer producer = session.createProducer(destination);
            /*等效替换
            QueueConnectionFactory connectionFactory = new  ActiveMQConnectionFactory(ActiveMQConnectionFactory.DEFAULT_USER,
                    ActiveMQConnectionFactory.DEFAULT_PASSWORD, "tcp://localhost:61616");
            connection = connectionFactory.createQueueConnection();
            connection.start();
            session = connection.createQueueSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
            Queue queue = session.createQueue("myqueue");
            QueueSender producer = session.createSender(queue);
             */
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
            for (int i = 0; i < 5; i++) {
                String message = "发送第" + (i + 1) + "条Queue消息";
                TextMessage textMessage = session.createTextMessage( message);
                System.out.println(message);
                producer.send(textMessage);
            }
            session.commit();
        } catch (Exception e) {
            throw e;
        } finally {
            // 关闭释放资源
            if (session != null) {
                session.close();
            }
            if (connection != null) {
                connection.close();
            }
        }
    }

}
